let merchantMap = new Map();

function addSocket(merchantId, socket) {
    merchantMap.set(merchantId, socket);
}

function notifyMerchant(merchantId) {
    if (merchantMap.has(merchantId)) {
        let theSocket = merchantMap.get(merchantId);
        // 使用当前socket来emit事件
        theSocket.emit('update');
    }
}

function removeAndDisconnectById(merchantId) {
    if (merchantMap.has(merchantId)) {
        let theSocket = merchantMap.get(merchantId);
        theSocket.disconnect();
        merchantMap.delete(merchantId);
        return true;
    } else {
        return false;
    }
}

function removeBySocket(socket) {
    for (let [key, value] of merchantMap.entries()) {
        if (value == socket) {
            merchantMap.delete(key);
            return true;
        }
    }
    return false;
}

module.exports.addSocket = addSocket;
module.exports.notifyMerchant = notifyMerchant;
module.exports.removeAndDisconnectById = removeAndDisconnectById;
module.exports.removeBySocket = removeBySocket;